package com.zcareu.logServ.service;

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogContent;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.GetLogsResponse;
import com.zcareu.logServ.entity.Filter;
import com.zcareu.logServ.repo.FilterRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.io.Serializable;
import java.util.*;

import static com.zcareu.logServ.service.AliyunConstant.*;

@Service
public class LogServ {
    private final static String LOG_STORE = "server-logs";

    private final static Client CLIENT = new Client(HOST, ACCESS_ID, ACCESS_KEY);

    @Autowired
    private FilterRepo filterRepo;

    public Filter addFilter(String name, String... queryStrings) {
        Filter filter = new Filter();

        filter.setName(name);
        filter.setQueries(new LinkedList<String>() {{
            for (String query : queryStrings)
                add(query);
        }});

        return filterRepo.save(filter);
    }

    public List<Map<String, Serializable>> getLogs(String filterName, String query, Date startWith, Date endWith, int line, int offset) {
        int from = (int) (startWith.getTime() / 1000);
        int to = (int) (endWith.getTime() / 1000 + 10);

        if (filterName != null) {
            Filter filter = null;
            try {
                filter = filterRepo.findByName(filterName);
            }catch (EntityNotFoundException ex) {
                //ignore
            }
            if(filter != null) {
                query = filter.merge(query);
            }
        }
        //System.out.println("query:" + query);
        List<Map<String, Serializable>> results = new LinkedList();

        try {
            GetLogsResponse logsResponse = CLIENT.GetLogs(PROJECT, LOG_STORE, from, to, "", query, line, offset, false);

            for (QueriedLog log : logsResponse.GetLogs()) {
                LogItem item = log.GetLogItem();
                Map record = new LinkedHashMap();
                record.put("time", item.mLogTime);
                for (LogContent content : item.mContents) {
                    record.put(content.mKey, content.mValue);
                }
                results.add(record);
            }
        } catch (LogException e) {
            throw new RuntimeException(e.getMessage());
        }

        return results;
    }


}
